package com.leonzhangxf.bucksdemo.order.infrastructure.repository.impl;

import com.leonzhangxf.bucksdemo.order.domain.Order;
import com.leonzhangxf.bucksdemo.order.domain.OrderRepository;
import com.leonzhangxf.bucksdemo.order.domain.value.OrderId;
import com.leonzhangxf.bucksdemo.order.infrastructure.repository.impl.dao.OrderDao;
import com.leonzhangxf.bucksdemo.order.infrastructure.repository.impl.po.OrderAssembler;
import com.leonzhangxf.bucksdemo.order.infrastructure.repository.impl.po.OrderPO;
import org.springframework.stereotype.Repository;

@Repository
public class OrderRepositoryImpl implements OrderRepository {

    private final OrderDao orderDao;

    private final OrderAssembler orderAssembler;

    public OrderRepositoryImpl(OrderDao orderDao) {
        this.orderDao = orderDao;
        this.orderAssembler = new OrderAssembler();
    }

    @Override
    public void saveOrder(Order order) {
        OrderPO orderPO = orderAssembler.createPo(order);
        orderDao.save(orderPO);
    }

    @Override
    public void updateOrder(Order order) {
        OrderPO orderPO = orderDao.getByOrderId(order.getOrderId().getId());
        if (null == orderPO) {
            return;
        }
        orderAssembler.copyDo(order, orderPO);
        orderDao.save(orderPO);
    }

    @Override
    public Order getById(OrderId orderId) {
        OrderPO orderPO = orderDao.getByOrderId(orderId.getId());
        return orderAssembler.createDo(orderPO);
    }
}
